<template>
    <div class="cover-box">
        <div class="cover-show">
            <img :src="uploadFile.uploadingUrl ? uploadFile.uploadingUrl : knowForm.color">
            <div class="cover-mark" v-if="uploadFile.uploadingUrl">
                <el-progress type="circle" :percentage="uploadFile.percentage" />
            </div>
        </div>
        <div class="select-cover-box" v-loading="coverLoading">
            <div class="type-box">
                <el-scrollbar style="width:calc(100% - 64px);">
                    <div class="type-items">
                        <div v-for="(item, index) in imgTypeList" :class="['type-item', item.value == imgType && 'active']"
                            :key="index" @click="imgTypeChange(item)">
                            {{ $t(item.label) }}
                        </div>
                    </div>
                </el-scrollbar>
                <div class="line"></div>
                <div class="upload-box">
                    <el-upload :http-request="handleRequest" :before-upload="beforeUpload" accept=".jpg,.jpeg,.png"
                        :show-file-list="false">
                        <div class="cover-upload-button">
                            <svg class="icon">
                                <use xlink:href="#keowledge-shangchuan"></use>
                            </svg>{{ $t('message.buttons.upload') }}
                        </div>
                    </el-upload>
                </div>
            </div>
            <div class="img-box">
                <el-scrollbar ref="coverRef">
                    <div :class="['img-item', item.url == knowForm.color && 'active']"
                        v-for="(item, index) in getCurrentTypeImg" :key="index" @click="selectCover(item)">
                        <img :src="item.url">
                    </div>
                </el-scrollbar>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    computed,
    onUnmounted,
    getCurrentInstance
} from 'vue'
import { useRouter } from "vue-router"
import { get } from '@/utils/request'
import { bigFileUpload } from '@/api/common'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();
const emit = defineEmits(["coverChange"])
const { proxy } = getCurrentInstance()
const props = defineProps({
    knowInfo: {
        type: Object,
        default() {
            return {}
        }
    },
})
const coverLoading = ref(false)
const imgType = ref('all')
const imgTypeList = ref([{
    label: 'message.text.all',
    value: 'all'
}])
const imgList = ref([])
const knowForm = ref({})
const coverRef = ref()
const uploadFile = ref({
    percentage: 0,
    isFinish: false,
    isUpload: false,
    uploadingUrl: ''
})
watch(() => props.knowInfo, (newV) => {
    knowForm.value = JSON.parse(JSON.stringify(newV))
})
onMounted(async () => {
    coverLoading.value = true
    await get("/jvs-public/img/resource.json").then(res => {
        if (res.status == 200) {
            let labelList = []
            imgList.value = res.data || []
            res.data.forEach((item) => {
                if (labelList.indexOf(item.label) == -1) {
                    labelList.push(item.label)
                    imgTypeList.value.push({
                        label: item.inter,
                        value: item.label
                    })
                }
            })
            coverLoading.value = false
        }
    }).catch(function (error) {
        uploadFile.value.uploadingUrl = ''
        coverLoading.value = false
    })
    knowForm.value = JSON.parse(JSON.stringify(props.knowInfo))
    if (!knowForm.value.color) {
        selectCover(getCurrentTypeImg.value[0])
    } else {
        const uploadCover = {
            label: $t('message.text.all'),
            value: knowForm.value.color,
            url: knowForm.value.color
        }
        selectCover(uploadCover)
        if (findCoverUrl(uploadCover)) {
            imgList.value.splice(0, 0, uploadCover)
        }
    }
})
function findCoverUrl(curCover) {
    for (let i = 0; i < imgList.value.length; i++) {
        if (imgList.value[i].url == curCover.url) {
            return false
            break
        }
    }
    return true
}
const getCurrentTypeImg = computed(() => {
    let arr = []
    imgList.value.forEach((item) => {
        if (item.label == imgType.value || imgType.value == 'all') {
            arr.push(item)
        }
    })
    return arr
})
function beforeUpload(file, type) {
    let ocrFileType = ['png', 'jpeg', 'jpg']
    let fileType = file.name.split(".").slice(-1)[0].toLowerCase()
    if (!ocrFileType.includes(fileType)) {
        proxy.$notify({
            title: $t('message.kindReminder'),
            message: $t('message.uploadImage'),
            type: 'warning',
            position: 'bottom-right'
        });
        return false
    }
    if (file.size / 1024 / 1024 > 1) {
        proxy.$notify({
            title: $t('message.kindReminder'),
            message: $t('message.uploadSize1M'),
            type: 'warning',
            position: 'bottom-right'
        });
        return false
    }
    return true
}
async function handleRequest(file, data) {
    uploadFile.value.uploadingUrl = URL.createObjectURL(file.file)
    uploadFile.value.isFinish = false
    uploadFile.value.isUpload = true
    uploadFile.value.percentage = 0
    let fetchForm = new FormData()
    fetchForm.append("file", file.file, file.file.name)
    fetchForm.append("module", "/jvs-knowledge-ui/jvs-knowledge-cover/")
    bigFileUpload(fetchForm, 'jvs-document-file', (e) => {
        uploadFile.value.percentage = parseInt(e) >= 99 ? 99 : parseInt(e)
    }).then(res => {
        const uploadCover = {
            label: $t('message.text.all'),
            value: res.data.data.originalFileName,
            url: res.data.data.fileLink
        }
        selectCover(uploadCover)
        imgList.value.splice(0, 0, uploadCover)
        uploadFile.value.uploadingUrl = ''
        uploadFile.value.isFinish = true
        uploadFile.value.isUpload = false
        uploadFile.value.percentage = 100
    }).catch(err => {
        uploadFile.value.isUpload = false
    })
}
function imgTypeChange(item) {
    imgType.value = item.value
    coverRef.value.setScrollTop(0)
}
function selectCover(item) {
    if (item?.url) {
        knowForm.value.color = item.url
        emit('coverChange', knowForm.value)
    }
}
function clearCover() {
    imgType.value = 'all'
    imgTypeList.value = [{
        label: 'message.text.all',
        value: 'all'
    }]
}
defineExpose({
    clearCover
})
</script>
<style lang="scss" scoped>
.cover-box {
    display: flex;

    .cover-show {
        width: 152px;
        height: 152px;
        overflow: hidden;
        border-radius: 6px;
        position: relative;

        img {
            width: 152px;
            height: 152px;
        }

        .cover-mark {
            display: flex;
            align-items: center;
            justify-content: center;
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0px;
            left: 0px;
            z-index: 9;
            background-color: rgba(255, 255, 255, 0.5);
        }
    }

    .select-cover-box {
        margin-left: 8px;
        width: calc(100% - 160px);

        .type-box {
            display: flex;
            align-items: center;
            height: 32px;

            .type-items {
                display: flex;
                align-items: center;
                width: calc(100% - 0px);
                box-sizing: border-box;
                font-size: 12px;
                word-break: keep-all;

                .type-item {
                    padding: 0px 8px;
                    height: 24px;
                    line-height: 24px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    cursor: pointer;
                    border-radius: 4px 4px 4px 4px;
                    @include SourceHanSansCN-Regular;
                    margin-right: 4px;

                    &:hover {
                        background: #E4EDFF;
                        color: #1E6FFF;
                    }
                }

                .active {
                    background: #E4EDFF;
                    color: #1E6FFF;
                }
            }

            .line {
                height: 24px;
                width: 1px;
                background-color: #d7d8db;
                margin-bottom: 8px;
            }

            .upload-box {
                height: 24px;
                // margin-bottom: 8px;
                margin-bottom: 4px;
                display: flex;
                width: 48px;
                color: #1E6FFF;
                font-size: 12px;

                .el-upload--text {
                    height: 24px;

                    .cover-upload-button {
                        width: 48px;
                        display: flex;
                        align-items: center;
                        @include SourceHanSansCN-Regular;
                        justify-content: center;

                        .icon {
                            width: 14px;
                            height: 14px;
                            margin-right: 4px;
                        }
                    }
                }
            }

        }

        .img-box {
            height: 120px;

            ::v-deep(.el-scrollbar__view) {
                display: grid;
                grid-template-columns: repeat(5, 1fr);
                flex-wrap: wrap;
                grid-column-gap: 8px;
                grid-row-gap: 8px;
                padding-right: 8px;
            }

            .img-item {
                height: 56px;
                width: 56px;
                cursor: pointer;
                border: 1px solid transparent;
                border-radius: 6px;
                overflow: hidden;

                img {
                    height: 56px;
                    width: 56px;
                }
            }

            .active {
                border-color: #1E6FFF;
            }
        }
    }
}
</style>